package validator

import (
	"io"
	"regexp"

	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

var trans ut.Translator

func RegisterCustomValidators() {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		zh := zh.New()
		uni := ut.New(zh, zh)
		trans, _ = uni.GetTranslator("zh")                    // 获取中文翻译器实例
		zh_translations.RegisterDefaultTranslations(v, trans) // 注册默认翻译

		// v.RegisterTranslation("required", trans, func(ut ut.Translator) error {
		// 	return ut.Add("required", "{0}是必填项", true)
		// }, func(ut ut.Translator, fe validator.FieldError) string {
		// 	t, _ := ut.T("required", fe.Field())
		// 	return t
		// })
	}
}

func TranslateValidateError(err error) ([]string, bool) {
	if validationErrors, ok := err.(validator.ValidationErrors); ok {
		errs := []string{}
		for _, e := range validationErrors {
			errs = append(errs, e.Translate(trans))
		}
		return errs, true
	} else if err == io.EOF {
		return []string{"未传递任何参数"}, true
	} else {
		return nil, false
	}
}

func IsPhoneNumber(val string) bool {
	re := regexp.MustCompile(`^1[3-9]\d{9}$`)
	return re.MatchString(val)
}

func GetTranslator() ut.Translator {
	return trans
}
